package icu.luoxi.config;

import icu.luoxi.interceptor.TokenInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor;
import org.springframework.web.servlet.config.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

/**
 * @author Cao Jiwen
 * @version V1.0
 */
@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport{

	@Resource
	private TokenInterceptor tokenInterceptor;

	/**
	 * 解决跨域请求
	 */
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**")
				.allowedHeaders("*")
				.allowedMethods("*")
				//.allowedOrigins("*")
				.allowedOriginPatterns("*")
				.allowCredentials(true);
	}

	/**
	 * 异步请求配置
	 */
	@Override
	public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
		configurer.setTaskExecutor(new ConcurrentTaskExecutor(Executors.newFixedThreadPool(3)));
		configurer.setDefaultTimeout(30000);
	}

	/**
	 * springboot 2.0配置WebMvcConfigurationSupport之后，会导致默认配置被覆盖，要访问静态资源需要重写addResourceHandlers方法
	 */
	@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/**")
				.addResourceLocations("classpath:/resources/")
				.addResourceLocations("classpath:/static/");

		registry.addResourceHandler("doc.html")
				.addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**")
				.addResourceLocations("classpath:/META-INF/resources/webjars/");

		super.addResourceHandlers(registry);
    }

	/**
	 * 配置拦截器、拦截路径
	 * 每次请求到拦截的路径，就会去执行拦截器中的方法
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		List<String> excludePath = new ArrayList<>();
		//排除拦截，除了注册登录(此时还没token)，其他都拦截
		excludePath.add("/user/login");  //登录
		excludePath.add("/user/register");     //注册
		excludePath.add("/file/uploads");     //文件上传
		excludePath.add("/upload/**");     //文件上传图片回显
		excludePath.add("/doc.html");     //swagger
		excludePath.add("/swagger-resources/**");     //swagger
		excludePath.add("/v2/api-docs");     //swagger
		excludePath.add("/webjars/**");     //swagger
		registry.addInterceptor(tokenInterceptor)
				.addPathPatterns("/**")
				.excludePathPatterns(excludePath);
		super.addInterceptors(registry);
	}
}
